#include "SelectController.h"
#include <QGraphicsScene>
#include <QGraphicsItem>
#include <QDebug>

SelectController::SelectController()
    : _satellites(4) // 四个方向
    , _current_item(nullptr)
    , _prev_item(nullptr)
{}

void SelectController::setScene(QGraphicsScene* scene)
{
    connect(scene, &QGraphicsScene::focusItemChanged, this, &SelectController::focusItemChanged);
}

void SelectController::setSatellite(SatelliteAdapter* adapter)
{
    if (adapter)
    {
        _satellites[static_cast<int>(adapter->getSatellitePosition())] = QPointer<SatelliteAdapter>(adapter);
        connect(this, &SelectController::satellitesInvisible, adapter, &SatelliteAdapter::invisible);
    }
}

void SelectController::connectRequest()
{
    SelectAdapter* cur_item = dynamic_cast<SelectAdapter*>(sender());
    if (cur_item)
    {
        qDebug() << "connectReqeust(" << cur_item << ")";
        emit satellitesInvisible(false);
        // 正式与前一个断联
        if (!_current_item.isNull())
        {
            for (int i = 0; i < _satellites.size(); ++i)
            {
                if (!_satellites[i].isNull())
                {
                    _current_item.data()->disconnect(_satellites[i].data());
                    _satellites[i].data()->disconnect(_current_item.data());
                }
            }
        }
        // 设置当前的SelectItem
        _current_item = cur_item;
        // 连接信号
        for (int i = 0; i < _satellites.size(); ++i)
        {
            if (!_satellites[i].isNull())
            {
                connect(_current_item.data(), &SelectAdapter::sendGeometry,
                        _satellites[i].data(), &SatelliteAdapter::receiveGeometry);

                connect(_current_item.data(), &SelectAdapter::geometryChanged,
                        _satellites[i].data(), &SatelliteAdapter::receiveGeometry);

                connect(_satellites[i].data(), &SatelliteAdapter::clicked,
                        _current_item.data(), &SelectAdapter::satelliteClicked);

                connect(_satellites[i].data(), &SatelliteAdapter::sendSelectToken,
                        _current_item.data(), &SelectAdapter::receiveSelectToken);
            }
        }
        // 发送请求坐标信息的信号，调整satellite的坐标
        emit _current_item->requestGeometry();
    }
}

void SelectController::focusItemChanged(QGraphicsItem *newFocusItem, QGraphicsItem *oldFocusItem, Qt::FocusReason reason)
{
    Q_UNUSED(oldFocusItem);
    Q_UNUSED(reason);
    qDebug() << newFocusItem;
    if (newFocusItem == nullptr)
    {
        emit satellitesInvisible(true);
    }
}

void SelectController::competitorRegister(SelectAdapter* adapter)
{
    if (adapter)
    {
        connect(adapter, &SelectAdapter::requestSelectToken, this, &SelectController::connectRequest);
    }
}
